package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.MaterielAdapter;
import com.glory.brepda.adapter.MultiEqpAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpEntity;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.LotactionList;
import com.glory.brepda.entity.MultiEqpBean;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class MultiEqpTrackInActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpid)
    FreeUI_ClearEditText etEqpid;
    @BindView(R.id.etQty)
    FreeUI_ClearEditText etQty;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.rvEqpList)
    RecyclerView rvEqpList;
    private MultiEqpAdapter mMultiEqpAdapter;

    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.tvpartName)
    TextView tvpartName;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvStepDesc)
    TextView tvStepDesc;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.eqpScan)
    ImageView eqpScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private AddCarrierDataAdapter materielBoxAdapter;
    private MaterielAdapter materielAdapter;
    private List<String> mDurablelist;
    private String mDurable;
    private String woid;
    private LotInfoEntity lotInfo;
    @Override
    protected int getLayoutResId() {
        return R.layout.multiequipment_layout;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
//        tvBaseSubmit.setVisibility(View.GONE);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        initRecyclerView(rvEqpList, this);
        mMultiEqpAdapter = new MultiEqpAdapter(null);
        mMultiEqpAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mMultiEqpAdapter.isFirstOnly(true);
        rvEqpList.setAdapter(mMultiEqpAdapter);

        initRecyclerView(rvMaterielBoxList, this);
        initRecyclerView(rvMaterielList, this);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);

        materielAdapter = new MaterielAdapter(null);
        materielAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielAdapter);

        initEdit(etEqpid, s->{
            if ("".equals(etLot.getText().toString())){
                showToast("请先扫描批次",false);
                return;
            }
            for (MultiEqpBean sMultiEqpBean : mMultiEqpAdapter.getData()){
                if (sMultiEqpBean.getEQUIPMENTID().equals(s)){
                    showToast("当前设备已添加到列表",false);
                    return;
                }
            }
            MultiEqpBean multiEqpBean = new MultiEqpBean();
            multiEqpBean.setLOTID(etLot.getText().toString());
            multiEqpBean.setEQUIPMENTID(getText(etEqpid));
            mMultiEqpAdapter.addData(0,multiEqpBean);
        });

        initEdit(etLot,s ->{
            LotUtils.searchLotInfo(MultiEqpTrackInActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity lot) {
                    lotInfo = lot;
                    LotInfoEntity.LotBean response = lot.getLOT();

                    Constant.LIMITPACKAGETYPEQTY = lot.getLIMITPACKAGETYPEQTY();
                    Constant.PACKAGETYPE = lot.getPACKAGETYPE();
                    Constant.WIRESPEC = lot.getWIRESPEC();
                    Constant.BDCODE = lot.getBD_CODE();
                    Constant.PARTNAME = lot.getLOT().getPARTNAME();

                    woid = response.getWOID();
                    mDurable = response.getDURABLEID();
                    tvBDNum.setText(lot.getBD_CODE());
                    mDurablelist = lot.getDURABLELIST();
                    tvLotState.setText(response.getSTATE());
                    tvpartName.setText(response.getPARTNAME());
                    tvStepDesc.setText(response.getSTEPDESC());
                    tvPackageType.setText(lot.getPACKAGETYPE());
                    tvPauseStatus.setText(lot.getLOT().getHOLDSTATE());
                    etEqpid.requestFocus();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

        initEdit(etMaterielBox, s -> {

            FreeApi_LogUtils.saveErrorMessages(s,"etMaterielBox");
            if (etLot.equals("")) {
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
            etMaterielBox.requestFocus();
        });
    }

    @Override
    protected void initData() {
        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        eqpScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etEqpid.setText(qrResult);
                        break;
                }
            }

        }
    }



    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (getText(etLot).equals("") || mMultiEqpAdapter.getData().size()==0){
                    showToast("请先扫描批次号或设备号",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                        (new TypeToken<BaseResponseBean<JSONObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(MultiEqpTrackInActivity.this,false,getSupportFragmentManager())){

                            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack2 = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                                    (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                                    }.getType(), getSupportFragmentManager(), this) {

                                @Override
                                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                                    super.onSuccess(response);
                                }
                                @Override
                                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                                    super.onError(response);
                                }
                            };
                            NetUtils.canceleqpidle(getText(etEqpid), new JsonParser().parse(new Gson().toJson(mMultiEqpAdapter.getData())).getAsJsonArray(), MultiEqpTrackInActivity.this, callBack2);


                            showToast("进站成功", true);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<JSONObject>> response) {
                        super.onError(response);
                        FreeApi_LogUtils.saveErrorMessages(response.getException(), "LOTTRACKIN");
                        FreeApi_ToastUtils.showFreeToast("连接服务器失败", MultiEqpTrackInActivity.this, false, 0);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "DefaultTrackIn");
                map.addProperty("TYPE", "0");
//                map.addProperty("ACTIONTYPE", "MutilEqpTrackIn");
                map.addProperty("ISCHECKSTEPAUTHORITY", true);
                map.addProperty("BDCODE", Constant.BDCODE);
                map.addProperty("LIMITPACKAGETYPEQTY", Constant.LIMITPACKAGETYPEQTY);
                map.addProperty("PACKAGETYPE", Constant.PACKAGETYPE);
                map.addProperty("PARTNAME", Constant.PARTNAME);
                map.addProperty("WIRESPEC", Constant.WIRESPEC);
                map.addProperty("ORDER_NO", lotInfo.getLOT().getWOID());
                map.addProperty("PARTTYPE", lotInfo.getLOT().getPARTTYPE());
                map.addProperty("CUSTOMERCODE", lotInfo.getLOT().getCUSTOMERCODE());
                map.addProperty("SPC2", lotInfo.getPART().getSPEC2());

                map.addProperty("EXPIRE_TIME", lotInfo.getFUTURETIMERINSTANCELIST().size() > 0?lotInfo.getFUTURETIMERINSTANCELIST().get(0).getEXPIRE_TIME():"");
                List<LotactionList> LotactionList = new ArrayList<>();
                LotactionList.add(new LotactionList(etLot.getText().toString(), "Comment", "", "", "", ""));

                List<LotList> lotList = new ArrayList<>();
                lotList.add(new LotList(etLot.getText().toString()));
                map.add("EQUIPMENTLIST", new JsonParser().parse(new Gson().toJson(mMultiEqpAdapter.getData())).getAsJsonArray());
                map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());
                map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(LotactionList)).getAsJsonArray());
                map.add("DURABLEIDLIST", new JsonParser().parse(new Gson().toJson(materielBoxAdapter.getData())).getAsJsonArray());
                NetUtils.requestPostNet("IF.LOTTRACKIN", "MULTIDEVICELOTTRACKIN", MultiEqpTrackInActivity.this, map, callBack);

                break;
        }
    }
}
